import React, { PureComponent } from "react";
import { View, StyleSheet, Text, SafeAreaView, DeviceEventEmitter, ToastAndroid } from "react-native";
import { Button, Icon, Overlay } from "react-native-tengits-elements";
import Swiper from "react-native-tengits-swiper";
import { TText } from "../common/Widgets/WidgetDefault";
import DataCenter from "../logic/DataCenter";
import { OverlayGateSelectList } from "./Components/GateSelectList";
import OverlayBatchBrightness from "./Components/BatchBrightness";
import {OverlayStrategyList} from "./Components/StrategyList";
import { scaleSize } from "../common/Utils/ToolUtils";
import { Colors, FontSize } from "../common/Theme/TTheme";
import ControlSubPage from "./Components/ControlSubPage";
import CommonDrawer from "../common/Widgets/CommonDrawer";
import UICommandExecute from "../logic/UICommandExecute";
import { OnlineStatusComponent, TSingleHoleEmptyView } from "./Components/SubItemComponent";
import { Adjust_Model, onlineStatus } from "../logic/LogicConstant";

export default class ControllPage extends React.PureComponent {
    constructor(props) {
        super(props);
        let colonys = DataCenter.getColonyExceptLocalCabinetData();
        this.state = {
            index:0,
            colonyCabinet: colonys,
            strategyList: DataCenter.getStrategyList(),
            selectDeviceVisible: false,
            batchBrightnessVisible: false,
            strategyListVisible: false,
            online: colonys && colonys.length > 0 ? colonys[0].onlineStatus : onlineStatus.OFFLINE,
        };
        this.cacheLight = {};
    }

    componentDidMount() {
        this.colonyCabinetListener = DeviceEventEmitter.addListener("colonyCabinet", ()=>{
            let colonys = DataCenter.getColonyExceptLocalCabinetData();
            let lastIndex = this.state.index;
            if(lastIndex >= colonys.length){
                lastIndex = Math.max(0, Math.min(lastIndex, colonys.length - 1));
            }
            this.setState({
                colonyCabinet: colonys,
                index: lastIndex,
                online: colonys?.[lastIndex]?.onlineStatus,
            });
        });
        this.strategyListListener = DeviceEventEmitter.addListener("strategyList", () =>{
            this.setState({
                strategyList: DataCenter.getStrategyList(),
            });
        });
    }

    componentWillUnmount() {
        this.colonyCabinetListener.remove();
        this.strategyListListener.remove();
    }

    getHeadTitle = ()=>{
        const{index, colonyCabinet} = this.state;
        let baseName = DataCenter.getTunnleBaseInfo();
        if(colonyCabinet && colonyCabinet.length > 0) {
            return baseName + colonyCabinet[index]?.gateName;
        } else {
            return baseName||"集群控制";
        }
    }

    renderHeader() {
        const{colonyCabinet} = this.state;
        if(colonyCabinet && colonyCabinet.length > 0) {
            return this.renderContentHeader();
        } else {
            return this.renderEmptyHeader();
        }
    }

    renderEmptyHeader() {
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
                <View style={{flex:1, alignItems:'center', flexDirection:'row', justifyContent:'center'}}>
                    <Text style={{fontSize: FontSize.h3_font, color:Colors.white}}>{`${this.getHeadTitle()}`}</Text>
                </View>
                </View>
    }

    renderContentHeader() {
        const{index, colonyCabinet, online} = this.state;
        return <View style={styles.header}>
                <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='menu' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.selectDrawer && this.selectDrawer.showModalAnimate()
                }}/>
            <View style={{flex:1, flexDirection:'row', alignItems:'center', justifyContent:'center'}}>
                {index > 0 ? <Button 
                    buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon size={scaleSize(40)} name='chevron-left' type='font-awesome' color={Colors.white}/>}
                    onPress={()=>{
                        const{index} = this.state;
                        let ret = Math.max(0, index-1);
                        this.setState({index: ret, online: colonyCabinet[ret].onlineStatus});
                }}/> : null}
                <View style={{flex:1, alignItems:'center', flexDirection:'row', justifyContent:'center'}}>
                    <Text style={{fontSize: FontSize.h3_font, color:Colors.white}}>{`${this.getHeadTitle()}`}</Text>
                    <View style={{alignItems:'center', justifyContent:'center', borderRadius:scaleSize(6), marginLeft: scaleSize(20), width:scaleSize(100), height:scaleSize(40), backgroundColor: "#FFAB2D"}}>
                    <Text style={{fontSize: FontSize.h4_font, color:Colors.white}}>{"非本柜"}</Text>
                    </View>
                    {online == onlineStatus.OFFLINE ?  <OnlineStatusComponent isOnline={false} containerStyle={{marginLeft: scaleSize(12)}}/> : null}
                </View>
                {index < ((colonyCabinet||[]).length-1) ? <Button
                    buttonStyle={{backgroundColor:'transparent', width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon size={scaleSize(40)} name='chevron-right' type='font-awesome' color={Colors.white}/>}
                    onPress={()=>{
                        const{index} = this.state;
                        let ret = Math.min((this.state.colonyCabinet||[]).length, index+1);
                        this.setState({index: ret, online: colonyCabinet[ret].onlineStatus});
                    }}
                    /> : null}
            </View>
            <Button 
                    buttonStyle={{borderRadius:0, backgroundColor:Colors.button_color, width:scaleSize(117), height:scaleSize(88)}} 
                    icon={<Icon name='sync-alt' type='MaterialIcons' color={Colors.white} size={scaleSize(40)}/>}
                    onPress={()=>{
                        this.setState({selectDeviceVisible: true});
                }}/>
        </View>
    }

    batchBtnCallback = (data)=>{
        const{index, colonyCabinet} = this.state;
        for(let i = 0; i < colonyCabinet[index].loop.length; i++) {
            let item = colonyCabinet[index].loop[i];
            this.cacheLight[item.loopNumber] = item.loopCurrentValue;
        }
        this.setState({
            batchBrightnessVisible: true,
        });
    }

    strateyBtnCallback = (data)=>{
        const{strategyList} = this.state;
        if(!strategyList || strategyList.length <= 0) {
            ToastAndroid.show("当前无策略配置", ToastAndroid.SHORT);
        } else {
            this.setState({strategyListVisible: true});
        }
    }

    sliderCallback = (data, loopItem, value) =>{
        UICommandExecute.onColonyRealSlider(data.gateId, [loopItem.loopNumber], value);
    }

    sliderCompleteCallback = (data, loopItem, value) =>{
        UICommandExecute.onColonySliderComplete(data.gateId, [loopItem.loopNumber], value, true);
    }

    batchSliderCallback = (data, loopNumbers, value) => {
        if(loopNumbers.length > 0) {
            UICommandExecute.onColonyRealSlider(data.gateId, loopNumbers, value);
        }
    }

    batchSliderCompleteCallback = (data, loopNumbers, value) => {
        for(let loop of loopNumbers) {
            this.cacheLight[loop] = value; 
        }
        if(loopNumbers.length > 0) {
            UICommandExecute.onColonySliderComplete(data.gateId, loopNumbers, value, false);
        }
    }

    toggleOverlay = (key, params) => {
        if(key == "GateSelect") {
            this.setState({selectDeviceVisible: false});
        } else if(key == "BatchBrightness") {
            const{index, colonyCabinet} = this.state;
            for(let i = 0 ; i < colonyCabinet[index].loop.length; i++) {
                let oriData = colonyCabinet[index].loop[i];
                if(this.cacheLight[oriData.loopNumber] != oriData.loopCurrentValue) {
                    UICommandExecute.onColonySliderComplete(colonyCabinet[index].gateId, [oriData.loopNumber], oriData.loopCurrentValue, false);
                }
            }
            this.setState({batchBrightnessVisible: false});
        } else if(key == "StrategySelect") {
            this.setState({strategyListVisible: false});
        }
    }

    onSure = (key, params) => {
        const{index, colonyCabinet} = this.state;
        if(key == "GateSelect") {
            this.setState({index: params},()=>{
                this.setState({selectDeviceVisible: false,
                    online: colonyCabinet[params].onlineStatus,
                    });
            });
        } else if(key == "BatchBrightness") {
            if(params.model == Adjust_Model.ADJUST_DIRECT_LIGHT) {
                UICommandExecute.onColonySliderComplete(colonyCabinet[index].gateId, params.loops, params.light, true);
            } else {
                UICommandExecute.onColonyStrategySelect(colonyCabinet[index].gateId, params.loops, params.strategy.id);
            }
            this.setState({batchBrightnessVisible: false});
        } else if(key == "StrategySelect") {
            this.setState({strategyListVisible: false});
        }
    }

    renderMenuDrawer() {
        const{navigation} = this.props;
        return <View style={{flex:1, flexDirection:'column', paddingHorizontal:scaleSize(44)}}>
                <Button buttonStyle={{height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"本控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('Main')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}} 
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"集群控制柜管控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"单洞分段调控"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('SingleHole')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"控制柜运行概览"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceSummary')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"设备信息"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('DeviceInfo')
                }}/>
                <Button buttonStyle={{marginTop:scaleSize(30), height:scaleSize(88), backgroundColor:Colors.button_color}}
                    titleStyle={{fontSize: FontSize.h4_font}}
                    title={"注册管理"} onPress={()=>{
                    this.selectDrawer && this.selectDrawer.hideModalAnimate();
                    navigation.replace('RegisterDevice')
                }}/>
            </View>
    }

    renderContent() {
        const{index, colonyCabinet, online} = this.state;
        if(colonyCabinet && colonyCabinet.length > 0) {
            return <ControlSubPage
                        key={colonyCabinet[index]?.gateName}
                        data={colonyCabinet[index]}
                        disabled={online == onlineStatus.OFFLINE}
                        batchBtnCallback={this.batchBtnCallback} 
                        sliderCompleteCallback={this.sliderCompleteCallback}
                        strateyBtnCallback={this.strateyBtnCallback}
                        sliderCallback={this.sliderCallback}/>
        } else {
            return <View style={{flex:1, paddingVertical:scaleSize(30), paddingHorizontal:scaleSize(85)}}>
                    <TSingleHoleEmptyView/>
                  </View>
        }
    }

    render() {
        const{index, colonyCabinet, strategyList, selectDeviceVisible, batchBrightnessVisible, strategyListVisible, online} = this.state;
        return <SafeAreaView style={styles.container}>
                {this.renderHeader()}
                {this.renderContent()}
                <CommonDrawer ref={(r) => {
                        this.selectDrawer = r;
                    }} contentView={this.renderMenuDrawer()}/>
                <Overlay overlayStyle={{padding:0}} isVisible={selectDeviceVisible} onBackdropPress={()=>{this.toggleOverlay("GateSelect")}} fullScreen>
                    <OverlayGateSelectList data={colonyCabinet} index={index} localIndex={-1}
                    toggleOverlay={this.toggleOverlay} onSure={this.onSure}/>
                </Overlay>
                <Overlay overlayStyle={{padding:0}} isVisible={batchBrightnessVisible} onBackdropPress={()=>{this.toggleOverlay("BatchBrightness")}} fullScreen>
                    <OverlayBatchBrightness data={colonyCabinet[index]}
                    sliderCallback={this.batchSliderCallback}
                    sliderCompleteCallback={this.batchSliderCompleteCallback}
                    toggleOverlay={this.toggleOverlay}
                    strategyList={strategyList}
                    onSure={this.onSure}/>
                </Overlay>
                <Overlay overlayStyle={{padding:0}} isVisible={strategyListVisible} onBackdropPress={()=>{this.toggleOverlay("StrategySelect")}} fullScreen>
                    <OverlayStrategyList data={strategyList} canSel={false} toggleOverlay={this.toggleOverlay} id={strategyList[0]?.id}/>
                </Overlay>
            </SafeAreaView>
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1, 
        backgroundColor: Colors.page_bg_color1, 
        justifyContent:'space-around'
    },
    header:{
        flexDirection: 'row',
        height: scaleSize(88),
        backgroundColor: Colors.navibar_color,
    },
});